package com.bmt.common;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bmt.core.BaseContoller;
import com.bmt.pos.bean.ModuleInfo;
import com.bmt.utils.String_Utils;

public class SecurityFilter extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("==>>Begin to Filter session====");
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		HttpSession session = request.getSession();
		String curPath = request.getRequestURL().toString();
		curPath = curPath.replace(basePath, "").replace("//", "/");
		System.out.println("===>>curpath:" + curPath);
		if (checkURL(curPath)) {
			LoginUser loginUser = (LoginUser) session.getAttribute(BaseContoller.LOGIN_USER);
			if (loginUser == null) {
				System.out.println("====>>go:" + indexPage);
				request.getRequestDispatcher(indexPage).forward(request, response);
				return false;
			} else {
				if (checkUserURL(loginUser, curPath)) {
					System.out.println("====>>go:" + e403Page);
					request.getRequestDispatcher(e403Page).forward(request, response);
					return false;
				}
			}
		}
		return super.preHandle(request, response, handler);

	}

	private boolean checkUserURL(LoginUser loginUser, String curPath) {
		for (ModuleInfo mi : loginUser.getUserMIList()) {
			String userUrl = "/" + mi.getUrl();
			if (String_Utils.isLike(curPath, userUrl)) {
				// usermgr/get/*.htm
				return false;
			}
		}
		return true;
	}

	private boolean checkURL(String curPath) {
		if (excludeList != null) {
			for (String var : excludeList)
				if (String_Utils.isLike(curPath, var)) {
					return false;
				}
		}
		return true;
	}

	private String mainPage;// = "/main.htm";
	private String indexPage;// = "/index.jsp";
	private String e403Page;
	private List<String> excludeList;

	public String getMainPage() {
		return mainPage;
	}

	public void setMainPage(String mainPage) {
		this.mainPage = mainPage;
	}

	public String getIndexPage() {
		return indexPage;
	}

	public void setIndexPage(String indexPage) {
		this.indexPage = indexPage;
	}

	public List<String> getExcludeList() {
		return excludeList;
	}

	public void setExcludeList(List<String> excludeList) {
		this.excludeList = excludeList;
	}

	public String getE403Page() {
		return e403Page;
	}

	public void setE403Page(String e403Page) {
		this.e403Page = e403Page;
	}

}
